package com.mapre.instance.manyTone;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/**
 * @author shengtao
 * @Description:
 * @date 2019/01/14 13:23
 */
public class ManyToOne extends Configured implements Tool{

    @Override
    public int run(String[] args) throws Exception {
        String nameNodeUrl = "hdfs://192.168.220.135:9000";
        String nameNodeName = "fs.defaultFS";
        Configuration configuration = new Configuration();
        configuration.set(nameNodeName, nameNodeUrl);
        Job job = Job.getInstance(configuration);
        job.setJarByClass(ManyToOne.class);

        job.setInputFormatClass(MyInputFormat.class);
        job.setOutputFormatClass(SequenceFileOutputFormat.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(BytesWritable.class);

        job.setMapperClass(FileMapper.class);

        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));

        boolean result = job.waitForCompletion(true);
        if (!result){
            return 1;
        }
        return 0;
    }

    static class FileMapper extends Mapper<NullWritable,BytesWritable,Text,BytesWritable>{

        private Text fileName;

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            InputSplit split = context.getInputSplit();
            Path file = ((FileSplit)split).getPath();
            fileName = new Text(file.getName());
        }

        @Override
        protected void map(NullWritable key, BytesWritable value, Context context) throws IOException, InterruptedException {
            context.write(fileName,value);
        }
    }

    public static void main(String[] args) throws Exception {
        int result = ToolRunner.run(new ManyToOne(),args);

        System.out.println("processed result is not success！");
    }

}
